<template>
  <div class="utilization-calendar">
    <el-row>
      <el-col :span="24">
        <dynForm
          :info-form="infoForm"
          :search-tags="searchTags"
          :select-list="selectList"
        >
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="doSearch"
          >
            {{ $t('search') }}</el-button>
        </dynForm>
      </el-col>
    </el-row>
    <el-card>
      <el-row>
        <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        />
      </el-row>
      <pagination
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        :total="total"
        @pagination="onChangePage"
      />
    </el-card>
  </div>
</template>
<script>
import mySetting from '@/mixins/mySetting'
import { getList } from '@/api/OEE/timeUtilization'
import { getEquipmentTypesList } from '@/api/production/layoutDesign'
import { getEqpModelList } from '@/api/equipment/eqpbase'
function getTime() {
  const year = new Date().getFullYear()
  const month = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
  return `${year}-${month}`
}

function getMonthAllWeeks(cur) {
  const currentY = Number(cur.split('-')[0])
  const currentM = Number(cur.split('-')[1])
  const currentTime = new Date()
  // 手动设置年月
  currentTime.setFullYear(currentY)
  currentTime.setMonth(currentM)
  currentTime.setDate(0)
  const lastDay = currentTime.getDate()

  currentTime.setDate(1)
  const startDay = currentTime.getDay()

  const allweeks = '日一二三四五六'.split('')
  const days = Array.from(Array(lastDay), (_, i) => {
    return allweeks[(startDay + i) % 7]
  })
  return days
}
export default {
  name: 'EqpStatusManage',
  mixins: [mySetting],
  data() {
    const searchTags = [
      // { label: this.$t('eqpType'), prop: 'eqpType', tag: 'DynSelect' },
      // { label: this.$t('eqpModel'), prop: 'eqpModel', tag: 'DynSelect' },
      { label: this.$t('eqpName'), prop: 'eqpId', tag: 'DynInput' },
      { label: this.$t('timeInterval'), prop: 'time', tag: 'Dyndate', datatype: 'month', dataformat: 'yyyy-MM', clearable: false }
    ]
    const tableColumns = [
      { prop: '', label: '', type: 'selection' },
      { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
        return (
          <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
        )
      } },
      { prop: 'eqpId', label: this.$t('eqpName') },
      { prop: 'agv', label: this.$t('averageValue') }
    ]
    return {
      infoForm: {
        time: getTime()
      },
      selectList: {},
      searchTags: Object.freeze(searchTags),
      tableColumns: tableColumns,
      tableLoading: true
    }
  },
  created() {
    this.initList()
    this.getEquipmentTypes()
    this.getEqpTypesList()
  },
  methods: {
    async initList() {
      this.tableData = []
      this.tableColumns = this.$options.data.call(this).tableColumns
      const res = await getList(this.$clearNull({ ...this.listQuery, ...this.infoForm }))
      const { data, days } = res.data
      this.tableColumns.push(...Array.from(Array(days), (_, i) => {
        return { prop: `timeU${i + 1}`, label: `${i + 1}星期(${getMonthAllWeeks(this.infoForm.time)[i]})`, width: '100px', templete: (_scope) => {
          return (
            <span style={{ display: 'inline-block', 'background': _scope.row[`timeU${i + 1}`].color, 'color': _scope.row[`timeU${i + 1}`].color ? '#fff' : '',
              'borderRadius': '4px', 'line-height': '30px', 'padding': '0 10px'
            }}>
              {_scope.row[`timeU${i + 1}`].timeU}
            </span>
          )
        } }
      }))
      const formatData = data.map((node) => {
        const { agv, eqpId, dataList } = node
        const timeInterval = dataList.reduce((acc, cur, idx) => {
          acc[`timeU${idx + 1}`] = {
            timeU: cur.timeU,
            color: cur.color
          }
          return acc
        }, {})

        return {
          agv,
          eqpId,
          ...timeInterval
        }
      })
      this.tableData = formatData
      this.total = res.total
      this.tableLoading = false
    },
    doSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    handleDelete() {
      this.$confirm(
        `${this.$t('confirmDelete')}${this.multipleSelection.length}${this.$t(
          'recordCount'
        )}?`,
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
      })
    },
    onChangePage(page) {
      this.listQuery = page
      this.initList()
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    // 获取设备类型列表
    async getEquipmentTypes() {
      const res = await getEquipmentTypesList()
      this.$set(this.selectList, 'eqpType', res.data)
    },
    async getEqpTypesList() {
      const res = await getEqpModelList()
      this.$set(this.selectList, 'eqpModel', res.data)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
::v-deep .el-row:nth-child(1) {
  padding-bottom: 0;
}
::v-deep .el-form {
  padding-top: 10px;
  // .el-form-item {
  //   margin-bottom: 15px;
  // }
}
</style>
